package com.abredatos.t37.core

import grails.converters.JSON 

class StationController {

	def stationService
	def pollutantDataService
	def measureCodes = ["unknown","ok","warning","risk"]
	
    def index = {
		 def stationList = stationService.loadAllStations()
		 def dataList = pollutantDataService.loadLastData()
		 def pollutantList = pollutantDataService.loadPollutants()
		 def pollutantData = buildPollutantData(pollutantList)
		 dataList = buildStationData(dataList)
		 
		 // General level for every station
		 def stationsLevelInfo = [:]
		 stationList.each { station ->
			 if (dataList[station.id.toString()] != null) {
				def maxMeasure = dataList[station.id.toString()].max { it.level }
				stationsLevelInfo[station.id] = maxMeasure.level
			 } else {
			 	stationsLevelInfo[station.id] = 0
			 }
		 }
		 render (view:"index", model: [stationList: stationList, dataList: dataList, stationsLevelInfo: stationsLevelInfo, measureCodes: measureCodes, pollutantData: pollutantData])
	}

	private buildStationData(dataList) {
		dataList.inject([:]) { stationData, measure ->
			if (stationData[measure.stationId.toString()] == null) {
				stationData[measure.stationId.toString()] = []
			}
			stationData[measure.stationId.toString()].add(measure)
			return stationData
		}
	}
	
	private buildPollutantData(pollutantList) {
		pollutantList.inject([:]) { pollutantData, pollutant ->
			pollutantData[pollutant.name.toString()] = pollutant
			return pollutantData
		}
	}
	
}
